﻿using InnoWeb.CEND.BL.Service;
using InnoWeb.CEND.BL.Service.Workshop;
using InnoWeb.CEND.Core.Model.Expert;
using InnoWeb.CEND.Core.Model.Workshop;
using InnoWeb.CEND.Data;
using InnoWeb.CEND.Data.Infrastructure;
using InnoWeb.CEND.UI.MVC.Areas.Admin.Models;
using InnoWeb.CEND.Web.Framework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace InnoWeb.CEND.UI.MVC.Areas.Admin.Controllers
{
    public class ProjectsController : Controller
    {
        private static WebSiteContext _context;
        private static IUnitOfWork _unitOfWork;

        private static GenericRepository<WorkshopItem> _workshopItemRepository;
        private static GenericRepository<WorkshopContent> _workshopContentRepository;
        private static WorkshopItemService _workshopItemService;
        private static WorkshopContentService _workshopContentService;

        private static GenericRepository<ExpertInfo> _expertInfoRepository;
        private static ExpertService _expertService;

        public ProjectsController()
        {
            _context = new WebSiteContext(ConfigurationManager.ConnectionStrings["CendDBConnection"].ConnectionString);
            _unitOfWork = new UnitOfWork(_context);

            _workshopContentRepository = new GenericRepository<WorkshopContent>(_context);
            _workshopItemRepository = new GenericRepository<WorkshopItem>(_context);

            _workshopItemService = new WorkshopItemService(_unitOfWork, _workshopItemRepository);
            _workshopContentService = new WorkshopContentService(_unitOfWork, _workshopContentRepository);

            _expertInfoRepository = new GenericRepository<ExpertInfo>(_context);

            _expertService = new ExpertService(_unitOfWork, _expertInfoRepository);
        }

        //
        // GET: /Admin/Projects/

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Index()
        {
            var itemList = _workshopItemService.GetAllElements().ToList();
            var contentList = _workshopContentService.GetAllElements().ToList();
            List<ProjectsModel> returnList = new List<ProjectsModel>();
            var list = (from nI in itemList
                        join nC in contentList on nI.Id equals nC.WorkshopItemId
                        select new
                        {
                            nI,
                            nC
                        });
            foreach (var item in list)
            {
                ProjectsModel obj = new ProjectsModel();
                obj.WorkshopContent = item.nC;
                obj.WorkshopItem = item.nI;
                returnList.Add(obj);
            }

            return View(returnList);
        }

        //
        // GET: /Admin/Projects/Details/5

        public ActionResult Details(int id)
        {
            var item = _workshopItemService.GetElementById(id);
            var content = _workshopContentService.GetAllElements().Where(a => a.WorkshopItemId == item.Id).FirstOrDefault();

            ProjectsModel obj = new ProjectsModel();
            obj.WorkshopContent = content;
            obj.WorkshopItem = item;
            return View(obj);
        }

        //
        // GET: /Admin/Projects/Create

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Create()
        {
            var itemList = _expertService.GetAllElements().ToList();
            ViewData["expertList"] = itemList;
            return View();
        }

        //
        // POST: /Admin/Projects/Create

        [HttpPost]
        public ActionResult Create(ProjectsModel model)
        {
            try
            {
                var img = Request.Files["fileUpload"];

                string fileName = Guid.NewGuid().ToString().Replace("-", "");
                string serverPath = Server.MapPath("~/Content/Images");
                //string imagesPath = serverPath + "Content\\Images\\";
                string thumbPath = Server.MapPath("~/Content/Images/Thumb");
                string fullPath = Server.MapPath("~/Content/Images/Full");

                ImageUploader.ImageSave(thumbPath, fullPath, img, fileName);

                WorkshopItem itemObj = model.WorkshopItem;
                itemObj.CreatedDate = DateTime.Today;
                itemObj.IsActive = true;
                itemObj.IsDeleted = false;
                itemObj.ModifiedDate = DateTime.Today;
                _workshopItemService.CreateElement(itemObj);
                _workshopItemService.SaveChanges();
                int a = itemObj.Id;

                WorkshopContent contentObj = model.WorkshopContent;
                contentObj.CreatedDate = DateTime.Today;
                contentObj.IsActive = true;
                contentObj.IsDeleted = false;
                contentObj.ModifiedDate = DateTime.Today;
                contentObj.ImageUrl =  fileName + ".jpg";
                contentObj.WorkshopItemId = a;
                _workshopContentService.CreateElement(contentObj);
                _workshopContentService.SaveChanges();

                Response.Write("<script type='text/javascript'>confirm(\"Data successfully added to database.\"); document.location = 'Index';</script>");

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Admin/Projects/Edit/5

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Edit(int id)
        {
            var item = _workshopItemService.GetElementById(id);
            var content = _workshopContentService.GetAllElements().Where(a => a.WorkshopItemId == item.Id).FirstOrDefault();

            var itemList = _expertService.GetAllElements().ToList();
            ViewData["expertList"] = itemList;

            ProjectsModel obj = new ProjectsModel();
            obj.WorkshopContent = content;
            obj.WorkshopItem = item;
            return View(obj);
        }

        //
        // POST: /Admin/Projects/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, ProjectsModel model)
        {
            try
            {

                var item = model.WorkshopItem;
                item.ModifiedDate = DateTime.Today;
                _workshopItemService.UpdateElement(item);
                _workshopItemService.SaveChanges();

                var content = model.WorkshopContent;
                content.WorkshopItemId = item.Id;
                content.ModifiedDate = DateTime.Today;

                var img = Request.Files["fileUpload"];

                if (img!=null)
                {
                    string fileName = Guid.NewGuid().ToString().Replace("-", "");
                    string serverPath = Server.MapPath("~/Content/Images");
                    //string imagesPath = serverPath + "Content\\Images\\";
                    string thumbPath = Server.MapPath("~/Content/Images/Thumb/");
                    string fullPath = Server.MapPath("~/Content/Images/Full/");

                    ImageUploader.ImageSave(thumbPath, fullPath, img, fileName);

                    content.ImageUrl =  fileName + ".jpg";
                }
                else
                {
                    content.ImageUrl = _workshopContentService.GetElementById(model.WorkshopContent.Id).ImageUrl;
                }
                
                _workshopContentService.UpdateElement(content);
                _workshopContentService.SaveChanges();

                var itemList = _expertService.GetAllElements().ToList();
                ViewData["expertList"] = itemList;
                return View(model);
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Admin/Projects/Delete/5

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Delete(int id)
        {
            ProjectsModel mdl = new ProjectsModel();
            var newsItem = _workshopItemService.GetElementById(id);
            var newsContent = _workshopContentService.GetAllElements().Where(a => a.WorkshopItemId == id).FirstOrDefault();
            mdl.WorkshopContent = newsContent;
            mdl.WorkshopItem = newsItem;

            return View(mdl);
        }

        //
        // POST: /Admin/Projects/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                var newsItem = _workshopItemService.GetElementById(id);
                var newsContent = _workshopContentService.GetAllElements().Where(a => a.WorkshopItemId == id).FirstOrDefault();

                newsItem.IsDeleted = true;
                newsItem.IsActive = false;

                newsContent.IsDeleted = true;
                newsContent.IsActive = false;

                _workshopItemService.UpdateElement(newsItem);
                _workshopItemService.SaveChanges();

                _workshopContentService.UpdateElement(newsContent);
                _workshopContentService.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
